package bs.jizhang.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {



    // 处理所有未捕获的异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleGlobalException(Exception ex, WebRequest request) {
        Map<String, Object> response = new HashMap<>();
        response.put("status", 500);
        response.put("msg", "系统内部错误: " + ex.getMessage());

        // 可以在这里添加额外的错误数据
        Map<String, Object> errorData = new HashMap<>();
        errorData.put("timestamp", System.currentTimeMillis());
        errorData.put("path", request.getDescription(false).substring(4)); // 移除"uri="前缀
        response.put("data", errorData);

        ex.printStackTrace();
        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    // 处理运行时异常
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<Map<String, Object>> handleBusinessException(BusinessException ex) {
        Map<String, Object> response = new HashMap<>();
        response.put("status", 5001);
        response.put("msg", ex.getMessage());
        response.put("data", ex.getData()); // 使用异常中携带的数据

        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }

}
